package com.sgzn.sgpay.service.impl;

import com.sgzn.sgpay.enums.SgsResponseCode;
import com.sgzn.sgpay.enums.TradeMark;
import com.sgzn.sgpay.exception.SgpayException;
import com.sgzn.sgpay.model.request.SgsMchAccountUpdateRequest;
import com.sgzn.sgpay.model.request.SgsMerchantQueryBaseRequest;
import com.sgzn.sgpay.model.response.SgsResultResponse;
import com.sgzn.sgpay.model.response.result.MerchantInfo;
import com.sgzn.sgpay.persistence.dao.TMerchantAccountMapper;
import com.sgzn.sgpay.persistence.domain.TMerchantAccount;
import com.sgzn.sgpay.persistence.domain.TMerchantAccountExample;
import com.sgzn.sgpay.service.SgsMchAccountService;
import com.sgzn.sgpay.service.SgsMerchantQueryService;
import com.sgzn.sgpay.service.converter.MerchantReqConverter;
import com.sgzn.sgpay.service.support.SgsResponseUtil;
import com.sgzn.sgpay.util.TranslateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 商户账户管理服务
 * @author zhongzhongyong
 * @version Id: SgsMchAccountServiceImpl.java, v 0.1 2018/4/17 22:19 zhongzhongyong Exp $$
 */
@Service
@Slf4j
@Transactional
public class SgsMchAccountServiceImpl implements SgsMchAccountService {

    @Autowired
    private SgsMerchantQueryService sgsMerchantQueryService;

    @Autowired
    private TMerchantAccountMapper tMerchantAccountMapper;

    /**
     * 更新商户账户信息,传递进来为需要变更的金额
     *
     * @param request
     * @return 商户ID
     */
    @Override
    public SgsResultResponse<String> updateAccountAmount(SgsMchAccountUpdateRequest request) {
        Lock lock = new ReentrantLock();
        lock.lock();
        try {
            log.info("update mchAccount credit start!!!");
            //检查商户账户是否存在
            SgsMerchantQueryBaseRequest queryReq = MerchantReqConverter.queryMchAccReqConvert(request);
            SgsResultResponse<MerchantInfo> mchResponse = sgsMerchantQueryService.queryMerchantInfo(queryReq);
            if (TranslateUtil.isSuccessAbs(mchResponse.getErrorCode()) && mchResponse.getResult() != null) {
                log.info("存在有效商户!!!");
                MerchantInfo mchInfo = mchResponse.getResult();
                BigDecimal hisAmount = mchInfo.getAccountAmount();
                BigDecimal trsAmount = new BigDecimal(request.getAmount());
                BigDecimal targetAmount = new BigDecimal(0);//最终结算积分额
                boolean checkPass = true;
                //若交易标记为'1',则需要检查减少的积分不能多于历史积分
                if (TradeMark.DECREASE.getCode().equals(request.getTradeMark())) {
                    if(trsAmount.compareTo(hisAmount) > 0){
                        checkPass = false;
                    }
                    targetAmount = hisAmount.subtract(trsAmount);
                }
                if (TradeMark.INCREASE.getCode().equals(request.getTradeMark())) {
                    targetAmount = hisAmount.add(trsAmount);
                }
                log.info("checkPass： {}", checkPass);
                //校验通过，执行积分增减
                if (checkPass) {
                    TMerchantAccount record = new TMerchantAccount();
                    record.setAccountAmount(targetAmount);
                    TMerchantAccountExample example = new TMerchantAccountExample();
                    TMerchantAccountExample.Criteria cra = example.createCriteria();
                    cra.andMerchantIdEqualTo(request.getMchId());
                    int num = tMerchantAccountMapper.updateByExampleSelective(record, example);
                    if (num > 0) {
                        log.info("积分增减成功！！！");
                        return SgsResponseUtil.INSTANCE.success("success");
                    } else {
                        log.info("积分增减失败！！！");
                        throw new SgpayException(SgsResponseCode.C_MERCHANT_ACCOUNT_UPDATE_ERR.getResponseCode(),
                                SgsResponseCode.C_MERCHANT_ACCOUNT_UPDATE_ERR.getResponseDesc());
                    }
                }else{
                    log.info("校验不通过!");
                    throw new SgpayException(SgsResponseCode.C_BALANCE_NOT_ENOUGH.getResponseCode(),
                            SgsResponseCode.C_BALANCE_NOT_ENOUGH.getResponseDesc());
                }
            } else {
                throw new SgpayException(SgsResponseCode.C_MERCHANT_NOT_FOUND.getResponseCode(),
                        SgsResponseCode.C_MERCHANT_NOT_FOUND.getResponseDesc());
            }
        } catch (SgpayException e) {
            log.error(" 业务异常 {},{}", e.getCode(), e.getDesc());
            return SgsResponseUtil.INSTANCE.fail(e.getCode(), e.getDesc());
        } catch (Exception e) {
            log.error(" 商户账户信息更新异常.", e);
            return SgsResponseUtil.INSTANCE.fail(SgsResponseCode.C503.getResponseCode(), SgsResponseCode.C503.getResponseDesc());
        } finally {
            lock.unlock();
        }
    }

}
